package com.tarena.verification;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * AOP 验证实现类
 * @author lsc
 *
 */
@Aspect
@Component
public class VerificationAspect {
	@Before("@annotation(Verification)")
	public void doBefore(JoinPoint joinPoint) throws Exception {
		System.out.println("do before ...");	
		
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
	    Method method = methodSignature.getMethod();
	    String organize = method.getAnnotation(Verification.class).organize();
		
		Object[] objects = joinPoint.getArgs();
		for(int i=0;i<objects.length;i++) {
			validate(objects[i],organize);
		}
	}
	/**
	 * 验证注解
	 * @param clazz		     方法参数类
	 * @param exception   是否抛出异常
	 * @return
	 * @throws Exception
	 */
	 public boolean validate(Object clazz,String organize) throws Exception {
	        Field[] fields = clazz.getClass().getDeclaredFields();
	        for (Field field : fields) {
	            //获取所有注解
	            Annotation [] annotations = field.getAnnotations();
	            for(int i=0;i<annotations.length;i++) {
	            	String name = annotations[i].annotationType().getName();
	            	
	                    Method m = clazz.getClass().getMethod("get" + (changeGet(field)));
	                    Object obj=m.invoke(clazz);
	                    Class<?> methodClass = Class.forName(name+"Method");
	                    methodClass.getMethod("valid",Annotation.class,Object.class,String.class).invoke(methodClass.newInstance(),annotations[i],obj,organize);
	            }
	        }
	        return true;
	  }
	//将字段首字母变为大写，get方法用
	private String changeGet(Field field) {
		if(field == null) {
			return "";
		}
		String name = field.getName();
		String be = name.substring(0, 1).toUpperCase();
		name = be+name.substring(1);
		return name;
	}
}
